<template>
  <div class="wallet-page">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <img src="../assets/icons/back.svg" class="back-icon" @click="goBack" />
      <span class="nav-title">钱包</span>
    </div>

    <!-- 钱包内容区域 -->
    <div class="wallet-container">
      <!-- 钱包图标 -->
      <img src="@/assets/icons/money.svg" class="money-icon"/>
      
      <!-- 余额显示 -->
      <div class="balance-section">
        <p class="balance-label">我的余额</p>
        <p class="balance-amount">￥{{ balance }}</p>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <div class="input-section" v-if="showAmountInput">
          <input 
            type="number" 
            v-model="amount" 
            :placeholder="inputPlaceholder"
            class="amount-input"
          />
          <button class="confirm-button" @click="handleConfirm">确认</button>
          <button class="cancel-button" @click="cancelOperation">取消</button>
        </div>
        <template v-else>
          <button class="recharge-button" @click="showRecharge">充值</button>
          <button class="withdraw-button" @click="showWithdraw">提现</button>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const balance = ref(0)
const amount = ref('')
const showAmountInput = ref(false)
const inputPlaceholder = ref('')
const currentOperation = ref('')

// 获取钱包余额
const fetchWalletBalance = async () => {
  try {
    const currentUser = JSON.parse(localStorage.getItem('user'))
    const userId = currentUser?.uid
    
    if (!userId) {
      console.error('未找到用户ID')
      return
    }

    const response = await axios.get('/api/auth/wallet', {
      headers: {
        'Authorization': localStorage.getItem('token'),
        'Content-Type': 'application/json'
      },
      data: {
        uid: userId
      }
    })

    if (response.data.code === 0) {
      balance.value = response.data.data.balance
    } else {
      console.error('获取余额失败:', response.data.message)
    }
  } catch (error) {
    console.error('获取钱包余额失败:', error)
  }
}

// 处理充值
const handleRecharge = async (amount) => {
  try {
    const currentUser = JSON.parse(localStorage.getItem('user'))
    const userId = currentUser?.uid

    if (!userId) {
      console.error('未找到用户ID')
      return false
    }

    const response = await axios.post('/api/auth/wallet/recharge', {
      uid: userId,
      amount: Number(amount)
    }, {
      headers: {
        'Authorization': localStorage.getItem('token'),
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 0) {
      await fetchWalletBalance() // 刷新余额
      return true
    } else {
      console.error('充值失败:', response.data.message)
      return false
    }
  } catch (error) {
    console.error('充值请求失败:', error)
    return false
  }
}

// 处理提现
const handleWithdraw = async (amount) => {
  try {
    const response = await axios.post('/api/auth/wallet/withdraw', {
      amount: Number(amount)
    }, {
      headers: {
        'Authorization': localStorage.getItem('token'),
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 0) {
      await fetchWalletBalance() // 刷新余额
      return true
    } else {
      console.error('提现失败:', response.data.message)
      return false
    }
  } catch (error) {
    console.error('提现请求失败:', error)
    return false
  }
}

// 确认操作
const handleConfirm = async () => {
  if (!amount.value || Number(amount.value) <= 0) {
    alert('请输入有效金额')
    return
  }

  try {
    let success = false
    if (currentOperation.value === 'recharge') {
      success = await handleRecharge(amount.value)
      if (success) {
        alert('充值成功')
      } else {
        alert('充值失败，请重试')
      }
    } else {
      if (Number(amount.value) > balance.value) {
        alert('余额不足')
        return
      }
      success = await handleWithdraw(amount.value)
      if (success) {
        alert('提现成功')
      } else {
        alert('提现失败，请重试')
      }
    }
    
    if (success) {
      showAmountInput.value = false
      amount.value = ''
    }
  } catch (error) {
    alert('操作失败，请重试')
  }
}

// 组件挂载时获取余额
onMounted(() => {
  fetchWalletBalance()
})

// 其他现有方法保持不变
const goBack = () => {
  router.push('/')
}

const showRecharge = () => {
  showAmountInput.value = true
  inputPlaceholder.value = '请输入充值金额'
  currentOperation.value = 'recharge'
}

const showWithdraw = () => {
  showAmountInput.value = true
  inputPlaceholder.value = '请输入提现金额'
  currentOperation.value = 'withdraw'
}

const cancelOperation = () => {
  showAmountInput.value = false
  amount.value = ''
}
</script>

<style scoped>
.wallet-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.nav-header {
  height: 61px;
  background: #ffffff;
  display: flex;
  align-items: center;
  padding: 0 10px;
  position: relative;
  z-index: 1;
}

.back-icon {
  width: 24px;
  height: 24px;
  cursor: pointer;
  margin-left: 5px;
  position: absolute;
  left: 10px;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 22px;
  font-weight: 500;
  font-family: "SourceHanFontBold";
  color: #333333;
}

.wallet-container {
  padding: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
  /* 移除可能导致容器过大的样式 */
  height: calc(100vh - 61px); /* 限制高度为视窗高度减去导航栏高度 */
  overflow-y: auto; /* 添加滚动条，以防内容过多 */
}

.money-icon {
  width: 100px;
  height: 100px;
  margin: 20px 0;
  object-fit: contain; /* 确保图标比例正确 */
  filter: invert(70%) sepia(11%) saturate(1066%) hue-rotate(176deg) brightness(94%) contrast(87%); /* 添加滤镜使图标变为 #9dbce3 颜色 */
}

.balance-section {
  text-align: center;
  margin: 20px 0;
}

.balance-label {
  font-size: 16px;
  color: #666;
  margin-bottom: 10px;
}

.balance-amount {
  font-size: 32px;
  font-weight: bold;
  color: #333;
}

.action-buttons {
  width: 100%;
  max-width: 340px;
  margin-top: 20px; /* 调整上边距 */
  padding: 0 15px; /* 添加左右内边距 */
}

.recharge-button,
.withdraw-button,
.confirm-button,
.cancel-button {
  width: 100%;
  height: 50px;
  margin: 10px 0;
  border: none;
  border-radius: 15px;
  font-size: 18px;
  cursor: pointer;
  transition: transform 0.2s ease-in-out;
}

.recharge-button {
  background: #9dbce3;
  color: white;
}

.withdraw-button {
  background: #f0f0f0;
  color: #333;
}

.confirm-button {
  background: #9dbce3;
  color: white;
}

.cancel-button {
  background: #f0f0f0;
  color: #333;
}

.input-section {
  width: 100%;
}

.amount-input {
  width: 100%;
  height: 50px;
  margin-bottom: 10px;
  padding: 0 15px;
  border: 1px solid #5b5b5b;
  border-radius: 8px;
  font-size: 16px;
  box-sizing: border-box;
  color: #5b5b5b; /* 添加文字颜色 */
}

.amount-input::placeholder {
  color: #5b5b5b; /* 添加占位符文字颜色 */
}

button:hover {
  transform: scale(1.02);
}
</style>